package com.xhxi.photobooker.controller;

import com.xhxi.photobooker.service.AiChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/ai")
public class AiChatController {
    @Autowired
    private AiChatService aiChatService;

    //后不再使用String 而改为流的形式
    @PostMapping("/chat")
    public String chat(@RequestParam String sessionId, @RequestBody String message) {
        return aiChatService.chat(sessionId, message);
    }
    //流式响应
    @PostMapping("/stream-chat")
    public ResponseBodyEmitter streamChat(@RequestParam String sessionId, @RequestBody String message) {
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
        new Thread(() -> {
            try {
                String systemPrompt = "你是摄影约拍平台的智能客服，你的名字叫'小影'。无论用户问什么，你都要以'小影'自称，并用简洁、礼貌、专业的语言回答用户。";

                String reqJson = "{" +
                        "\"model\":\"qwen2:1.5b\"," +
                        "\"messages\":[" +
                        "{\"role\":\"system\",\"content\":\"" + systemPrompt + "\"}," +
                        "{\"role\":\"user\",\"content\":\"" + message + "\"}" +
                        "]," +
                        "\"temperature\":0.7," +
                        "\"max_tokens\":512" +
                        "}";

                URL url = new URL("http://localhost:11434/api/chat");

                //创建连接：(HttpURLConnection) url.openConnection()
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //设置请求头和方法：setRequestMethod("POST")、setRequestProperty("Content-Type", "application/json")
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);//设置响应
                //写入请求体：通过 OutputStream 写入 JSON 数据
                try (OutputStream os = conn.getOutputStream()) {
                    os.write(reqJson.getBytes(StandardCharsets.UTF_8));
                }
                //读取响应：通过 BufferedReader 逐行读取流式响应
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        emitter.send(line + "\n");
                    }
                }
                emitter.complete();
            } catch (Exception e) {
                try { emitter.completeWithError(e); } catch (Exception ignored) {}
            }
        }).start();
        return emitter;
    }
} 